<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="员工姓名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入员工姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          v-hasPermi="['system:assessUser:list']"
        >搜索</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <div v-loading="loading">
      <el-collapse v-model="activeRoles" accordion>
        <el-collapse-item v-for="(group, idx) in rolesWithUsers" :key="group.roleKey || idx" :name="group.roleKey || String(idx)">
          <template slot="title">
            <span>角色：{{ group.roleName || '未分配角色' }}（{{ group.users.length }}人）</span>
          </template>
          <el-table :data="group.users" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="员工姓名" align="center" prop="userName" />
            <el-table-column label="部门" align="center" prop="deptName" />
            <el-table-column label="手机号码" align="center" prop="phonenumber" />
            <el-table-column label="状态" align="center" prop="status" width="100">
              <template slot-scope="scope">
                <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">
                  {{ scope.row.status === '0' ? '正常' : '停用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="审核状态" align="center" width="150">
              <template slot-scope="scope">
                <div class="audit-status-display">
                  <!-- 主管审核状态 -->
                  <div class="audit-role-row">
                    <span class="role-label">主管:</span>
                    <el-tag 
                      :type="scope.row.supervisorAudited ? 'success' : 'info'"
                      size="mini"
                    >
                      {{ scope.row.supervisorAudited ? '已审核' : '未审核' }}
                    </el-tag>
                  </div>
                  
                  <!-- 经理审核状态 -->
                  <div class="audit-role-row">
                    <span class="role-label">经理:</span>
                    <el-tag 
                      :type="scope.row.managerAudited ? 'success' : 'info'"
                      size="mini"
                    >
                      {{ scope.row.managerAudited ? '已审核' : '未审核' }}
                    </el-tag>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" width="180">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-view"
                  @click="handleViewCalendar(scope.row)"
                >查看考核</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>
      </el-collapse>
    </div>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 日历选择对话框 -->
    <el-dialog 
      title="选择考核日期" 
      :visible.sync="calendarOpen" 
      width="600px" 
      append-to-body
      :close-on-click-modal="false"
      class="calendar-dialog"
      @open="handleCalendarOpen"
    >
      <div class="calendar-container">
        <div class="calendar-header">
          <span class="calendar-title">请选择要查看的考核日期</span>
          <span class="user-info">员工：{{ selectedUserInfo.userName || '' }}</span>
        </div>
        <el-calendar v-model="selectedDate" @select="handleDateSelect" v-loading="loading">
          <template slot="dateCell" slot-scope="{date, data}">
            <div class="calendar-day" 
                 :class="[getDayClass(data), { 'rest-day': isRestDay(data.day) }]" 
                 @click="handleDayClick(data)">
              <span class="day-number">{{ data.day.split('-').slice(2).join('') }}</span>
              
              <!-- 休息日标记 -->
              <div v-if="isRestDay(data.day)" class="rest-indicator">
                <i class="el-icon-sunny"></i>
                <span>休息</span>
              </div>
              
              <!-- 只在非休息日显示审核状态 -->
              <div v-if="!isRestDay(data.day)" class="audit-status-container">
                <!-- 主管审核状态 -->
                <div class="audit-role-status supervisor-status" :class="getSupervisorStatusClass(data.day)">
                  <span class="role-label">主</span>
                </div>
                <!-- 经理审核状态 -->
                <div class="audit-role-status manager-status" :class="getManagerStatusClass(data.day)">
                  <span class="role-label">经</span>
                </div>
              </div>
            </div>
          </template>
        </el-calendar>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="calendarOpen = false">取 消</el-button>
        <el-button type="primary" @click="handleTodayClick">查看今日考核</el-button>
      </div>
    </el-dialog>

    <!-- 考核详情对话框 -->
    <el-dialog 
      :title="`${selectedUserInfo.userName || ''} - ${selectedDateForDetail} 考核详情`"
      :visible.sync="detailOpen" 
      width="95%" 
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      class="detail-dialog"
      :before-close="handleDetailClose"
    >
      <div class="detail-header">
        <div class="detail-info">
          <span class="detail-title">考核详情</span>
          <span class="detail-date">{{ selectedDateForDetail }}</span>
          <span class="detail-user">员工：{{ selectedUserInfo.userName || '' }}</span>
        </div>
        <el-button 
          type="text" 
          icon="el-icon-close" 
          @click="detailOpen = false"
          class="close-btn"
        ></el-button>
      </div>
      <assess-user-detail 
        v-if="detailOpen" 
        :selected-date="selectedDateForDetail"
        :user-id="selectedUserId"
        :is-popup="true"
        @close="detailOpen = false"
      />
    </el-dialog>
  </div>
</template>

<script>
import { getAssessRolesWithUsers } from "@/api/system/assessUser"
import { getCalendarData } from "@/api/assessUser"
import { getRestDays } from "@/api/system/assessScore"
import AssessUserDetail from './detail.vue'

export default {
  name: "AssessUserAudit",
  components: {
    AssessUserDetail
  },
  data() {
    return {
      // 遮罩层
      loading: true,
            // 选中数组
      ids: [],
      // 折叠面板激活角色
      activeRoles: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 角色+用户数据（后端已分组）
      rolesWithUsers: [],
      // 日历对话框
      calendarOpen: false,
      // 详情对话框
      detailOpen: false,
      // 选中的日期
      selectedDate: new Date(),
      // 传递给详情页的日期
      selectedDateForDetail: '',
      // 选中的用户ID
      selectedUserId: null,
      // 查询参数
      queryParams: {
        userName: null
      },
      // 月度审核状态数据
      monthlyAuditStatus: {},
      // 选中的用户信息
      selectedUserInfo: {},
      // 防抖定时器
      debounceTimer: null,
      // 休息日列表
      restDays: []
    }
  },
  created() {
      this.getList()
  },
  beforeDestroy() {
    // 清理防抖定时器
    if (this.debounceTimer) {
      clearTimeout(this.debounceTimer)
      this.debounceTimer = null
    }
  },
  watch: {
    // 监听selectedDate变化，当月份改变时重新获取数据
    selectedDate: {
      handler(newDate, oldDate) {
        // 如果日历对话框打开且选中了用户，则重新获取数据
        if (this.calendarOpen && this.selectedUserId && newDate && oldDate) {
          // 检查月份是否真的改变了
          const newMonth = newDate.getMonth()
          const oldMonth = oldDate.getMonth()
          const newYear = newDate.getFullYear()
          const oldYear = oldDate.getFullYear()
          
          if (newMonth !== oldMonth || newYear !== oldYear) {
            console.log('月份改变，重新获取数据:', {
              from: `${oldYear}-${oldMonth + 1}`,
              to: `${newYear}-${newMonth + 1}`
            })
            // 防抖处理，避免频繁调用
            if (this.debounceTimer) {
              clearTimeout(this.debounceTimer)
            }
            this.debounceTimer = setTimeout(() => {
              this.getCalendarData(this.selectedUserId)
            }, 300) // 300ms防抖
          }
        }
      },
      deep: true
    }
  },
  methods: {
    /** 查询可管理的角色及其员工 */
    getList() {
      this.loading = true
      getAssessRolesWithUsers(this.queryParams).then(response => {
        // response.data: [{ roleId, roleName, roleKey, users: SysUser[] }]
        this.rolesWithUsers = response.data || []
        this.loading = false
      }).catch(error => {
        this.loading = false
        console.error('获取用户列表失败:', error)
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 查看考核日历 */
    async handleViewCalendar(row) {
      this.selectedUserId = row.userId
      this.selectedUserInfo = row // 存储用户信息
      this.calendarOpen = true
      
      // 清空之前的审核状态数据，确保显示最新数据
      this.monthlyAuditStatus = {}
      
      // 一次性获取所有日历数据（强制刷新）
      await this.getCalendarData(row.userId, true)
    },
    
    /** 日历对话框打开时的处理 */
    handleCalendarOpen() {
      // 每次打开对话框都刷新数据，确保显示最新信息
      if (this.selectedUserId) {
        console.log('日历对话框打开，刷新实时数据...')
        this.getCalendarData(this.selectedUserId, true) // 强制刷新
      }
    },
    /** 获取日历综合数据（一次性获取所有数据） */
    async getCalendarData(userId, forceRefresh = false) {
      try {
        // 显示加载状态
        this.loading = true
        
        const yearMonth = this.formatDate(this.selectedDate, 'yyyy-MM')
        console.log(`正在获取 ${yearMonth} 的日历数据...`)
        
        // 添加时间戳防止缓存，确保获取最新数据
        const timestamp = forceRefresh ? Date.now() : null
        const response = await getCalendarData(yearMonth, userId, timestamp)
        if (response.code === 200) {
          const data = response.data || {}
          
          // 只设置月度审核状态数据
          this.monthlyAuditStatus = data.monthlyAuditStatus?.dailyAuditStatus || {}
          
          console.log(`${yearMonth} 审核状态数据加载完成:`, {
            monthlyAuditStatus: this.monthlyAuditStatus
          })
          
          this.$message.success(`${yearMonth} 审核状态数据加载完成`)
        } else {
          this.monthlyAuditStatus = {}
          this.$message.warning('审核状态数据加载失败')
        }
        
        // 获取休息日数据
        await this.loadRestDays(yearMonth, userId)
      } catch (error) {
        console.error('获取审核状态数据失败:', error)
        this.monthlyAuditStatus = {}
        this.$message.error('审核状态数据加载失败: ' + error.message)
      } finally {
        this.loading = false
      }
    },
    /** 日期选择处理 */
    handleDateSelect(date) {
      this.selectedDateForDetail = this.formatDate(date, 'yyyy-MM-dd')
      this.calendarOpen = false
      this.detailOpen = true
    },
    /** 格式化日期 */
    formatDate(date, format) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      
      return format
        .replace('yyyy', year)
        .replace('MM', month)
        .replace('dd', day)
    },
    /** 获取日期样式类 */
    getDayClass(data) {
      const today = new Date()
      const date = new Date(data.day)
      
      if (date.toDateString() === today.toDateString()) {
        return 'today'
      }
      return ''
    },
    /** 处理日历日期点击 */
    handleDayClick(data) {
      this.selectedDate = new Date(data.day)
      this.handleDateSelect(this.selectedDate)
    },
    /** 处理查看今日考核 */
    handleTodayClick() {
      this.selectedDate = new Date()
      this.handleDateSelect(this.selectedDate)
    },
    
    /** 获取某天的审核状态 */
    getDayAuditStatus(day) {
      return this.monthlyAuditStatus[day] || { supervisorAudited: false, managerAudited: false }
    },
    
    /** 获取主管审核状态样式类 */
    getSupervisorStatusClass(day) {
      const status = this.getDayAuditStatus(day)
      if (!status) return ''
      
      return status.supervisorAudited ? 'audited' : 'not-audited'
    },
    
    /** 获取经理审核状态样式类 */
    getManagerStatusClass(day) {
      const status = this.getDayAuditStatus(day)
      if (!status) return ''
      
      return status.managerAudited ? 'audited' : 'not-audited'
    },
    
    /** 详情对话框关闭前的处理 */
    handleDetailClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },
    
    /** 加载休息日数据 */
    async loadRestDays(yearMonth, userId) {
      try {
        const res = await getRestDays(yearMonth, userId)
        this.restDays = res.data || []
      } catch (error) {
        console.error('获取休息日数据失败:', error)
        this.restDays = []
      }
    },
    
    /** 判断是否为休息日 */
    isRestDay(day) {
      return this.restDays.includes(day)
    }
  }
}
</script>

<style scoped>
.calendar-dialog .el-dialog__body {
  padding: 20px;
}

.calendar-dialog .el-dialog__footer {
  padding: 10px 20px;
  border-top: 1px solid #ebeef5;
}

.calendar-container {
  max-height: 500px;
  overflow-y: auto;
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding: 10px 0;
  border-bottom: 2px solid #409EFF;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 8px;
  padding: 15px;
}

.calendar-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.user-info {
  font-size: 14px;
  color: #666;
  background: rgba(64, 158, 255, 0.1);
  padding: 5px 10px;
  border-radius: 15px;
  border: 1px solid #409EFF;
}

.calendar-day {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: relative;
  min-height: 50px;
  cursor: pointer;
  border-radius: 8px;
  transition: all 0.3s ease;
  border: 1px solid transparent;
}

.calendar-day:hover {
  background-color: #f0f9ff;
  border-color: #409EFF;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
}

.day-number {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.day-score {
  font-size: 10px;
  font-weight: bold;
  margin-top: 2px;
  padding: 2px 6px;
  border-radius: 10px;
  min-width: 24px;
  text-align: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.score-high {
  background: linear-gradient(135deg, #67C23A, #85ce61);
  color: white;
}

.score-medium {
  background: linear-gradient(135deg, #E6A23C, #ebb563);
  color: white;
}

.score-low {
  background: linear-gradient(135deg, #F56C6C, #f78989);
  color: white;
}

.today {
  background: linear-gradient(135deg, #409EFF, #66b1ff);
  color: white;
  border: 2px solid #409EFF;
}

.today .day-number {
  color: white;
  font-weight: bold;
}

.today .day-score {
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.assess-indicator {
  position: absolute;
  top: 2px;
  right: 2px;
  background: linear-gradient(135deg, #409EFF, #66b1ff);
  color: white;
  border-radius: 50%;
  width: 18px;
  height: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 10px;
  border: 2px solid white;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.4);
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    transform: scale(1);
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.4);
  }
  50% {
    transform: scale(1.1);
    box-shadow: 0 4px 16px rgba(64, 158, 255, 0.6);
  }
  100% {
    transform: scale(1);
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.4);
  }
}

.detail-dialog .el-dialog__header {
  padding: 15px 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-bottom: 2px solid #409EFF;
  border-radius: 8px 8px 0 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.detail-dialog .el-dialog__header .el-dialog__title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.detail-dialog .el-dialog__header .el-dialog__headerbtn {
  top: 15px;
  right: 15px;
}

.detail-dialog .el-dialog__header .el-dialog__headerbtn .el-icon-close {
  font-size: 22px;
  color: #909399;
  transition: all 0.3s ease;
}

.detail-dialog .el-dialog__header .el-dialog__headerbtn:hover .el-icon-close {
  color: #F56C6C;
  transform: scale(1.1);
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding: 15px;
  border-bottom: 2px solid #ebeef5;
  background: #fafafa;
  border-radius: 8px;
}

.detail-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.detail-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.detail-date {
  font-size: 14px;
  color: #666;
  background: rgba(64, 158, 255, 0.1);
  padding: 5px 12px;
  border-radius: 15px;
  border: 1px solid #409EFF;
}

.detail-user {
  font-size: 14px;
  color: #666;
  background: rgba(103, 194, 58, 0.1);
  padding: 5px 12px;
  border-radius: 15px;
  border: 1px solid #67C23A;
}

.close-btn {
  padding: 8px 12px;
  margin-left: 10px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.close-btn:hover {
  background-color: #f56c6c;
  color: white;
  transform: scale(1.05);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .calendar-dialog {
    width: 95% !important;
  }
  
  .detail-dialog {
    width: 98% !important;
  }
  
  .calendar-header {
    flex-direction: column;
    gap: 10px;
    text-align: center;
  }
  
  .detail-info {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }
}

/* 审核状态显示样式 */
.audit-status-display {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.audit-role-row {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
}

.role-label {
  font-weight: bold;
  color: #606266;
  min-width: 30px;
}

/* 日历审核状态容器 */
.audit-status-container {
  position: absolute;
  bottom: 2px;
  left: 2px;
  right: 2px;
  display: flex;
  justify-content: space-between;
  gap: 2px;
  font-size: 8px;
}

/* 审核角色状态 */
.audit-role-status {
  display: flex;
  align-items: center;
  gap: 2px;
  padding: 2px 4px;
  border-radius: 6px;
  font-weight: bold;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;
  flex: 1;
  justify-content: center;
  min-width: 0;
}

.audit-role-status .role-label {
  font-size: 9px;
  font-weight: bold;
  text-align: center;
  width: 100%;
  display: block;
}

/* 主管审核状态 */
.supervisor-status.audited {
  background: linear-gradient(135deg, #F56C6C, #f78989);
  color: white;
  border: 1px solid #f24545;
}

.supervisor-status.not-audited {
  background: white;
  color: #333;
  border: 1px solid #ddd;
}

/* 经理审核状态 */
.manager-status.audited {
  background: linear-gradient(135deg, #F56C6C, #f78989);
  color: white;
  border: 1px solid #f24545;
}

.manager-status.not-audited {
  background: white;
  color: #333;
  border: 1px solid #ddd;
}

/* 今日状态下的审核状态 */
.today .audit-role-status {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}

.today .supervisor-status.audited {
  background: rgba(245, 108, 108, 0.9);
  color: white;
}

.today .supervisor-status.not-audited {
  background: rgba(255, 255, 255, 0.9);
  color: #333;
}

.today .manager-status.audited {
  background: rgba(245, 108, 108, 0.9);
  color: white;
}

.today .manager-status.not-audited {
  background: rgba(255, 255, 255, 0.9);
  color: #333;
}

/* 日历日期悬停效果 */
.calendar-day:hover .audit-role-status {
  transform: scale(1.05);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}

/* 响应式调整 */
@media (max-width: 768px) {
  .audit-status-container {
    font-size: 7px;
  }
  
  .audit-role-status {
    padding: 1px 2px;
    gap: 1px;
  }
  
  .audit-role-status .role-label {
    font-size: 8px;
  }
}

/* 休息日样式 - 绿色背景 */
.rest-day {
  background: linear-gradient(135deg, #67C23A, #85ce61) !important;
  color: white !important;
}

.rest-day .day-number {
  color: white !important;
  font-weight: bold;
}

.rest-indicator {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-size: 10px;
  color: white;
  margin-top: 4px;
}

.rest-indicator i {
  font-size: 14px;
  margin-bottom: 2px;
}

/* 休息日悬停效果 */
.calendar-day.rest-day:hover {
  background: linear-gradient(135deg, #5DAF34, #67C23A) !important;
  border-color: #5DAF34 !important;
}

</style>
